<template>
  <div class="edit-page-wrap">
    <Head title="基本信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="edit-form-wrap"
        >
          <el-form-item label="任务名称" prop="name">
            <el-input
              v-model.trim="ruleForm.name"
              placeholder="请输入任务名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item label="任务支付钱包" prop="originalAccountId">
            <qc-select
              v-if="!id"
              :value="ruleForm.originalAccountId"
              :remote="true"
              :filterable="true"
              :options="optionsS.org"
              placeholder="请选择任务支付钱包"
              @change="handleChangeOrg"
            >
            </qc-select>
            <div v-else>{{ ruleForm.originalAccountName }}</div>
          </el-form-item>
          <el-form-item label="任务模式" prop="taskType">
            <el-radio-group
              v-model="ruleForm.taskType"
              v-for="(item, index) in TASK_TYPE"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="金额" prop="amount">
            <el-input
              v-model.trim="ruleForm.amount"
              placeholder="请输入金额"
              clearable
            />
          </el-form-item>
          <el-form-item label="执行目标" prop="targetType" class="has-tips">
            <el-radio-group
              v-model="ruleForm.targetType"
              v-for="(item, index) in targetTypeData"
              :key="index"
              @change="handleTargetType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip" v-if="ruleForm.targetType">
              <div class="icon"></div>
              <span v-if="ruleForm.targetType == '0'"
                >选定企业后，该企业所有用户均为发放目标，含任务执行前新增的用户</span
              >
              <span v-if="ruleForm.targetType == '1'"
                >选定标签后，该标签内所有均为发放目标，标签用户添加、删除会同步更新</span
              >
              <span v-if="ruleForm.targetType == '2'"
                >注：请输入用户的账号，多个账号之间用英文','隔开</span
              >
            </div>
          </el-form-item>
          <el-form-item
            label=""
            prop="treeId"
            v-if="ruleForm.targetType == '0'"
          >
            <QcTree
              ref="companyTree"
              :data="optionsS.treeData"
              :showCheckbox="true"
              :checkStrictly="true"
              :setCheckedKeys="optionsS.setCompanyChecked"
              @handleCheck="handleCheck"
            ></QcTree>
          </el-form-item>
          <el-form-item
            label=""
            prop="treeId1"
            v-if="ruleForm.targetType == '1'"
          >
            <QcTree
              ref="labelTree"
              :data="optionsS.labelTreeData"
              :showCheckbox="true"
              :setCheckedKeys="optionsS.setLabelChecked"
              @handleCheck="handleCheck1"
            ></QcTree>
          </el-form-item>
          <el-form-item label="" v-if="ruleForm.targetType == '2'">
            <el-button type="primary" plain @click="uploadUser"
              >批量导入</el-button
            >
          </el-form-item>
          <el-form-item prop="userTargetIds" v-if="ruleForm.targetType == '2'">
            <el-input
              v-model.trim="ruleForm.userTargetIds"
              placeholder="请输入用户账号"
              type="textarea"
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <div class="edit-line"></div>
    <Head title="执行模式">
      <template #content>
        <el-form
          ref="ruleFormOtherRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="edit-form-wrap"
        >
          <el-form-item label="选择模式" prop="executeType">
            <el-radio-group
              v-model="ruleForm.executeType"
              v-for="(item, index) in EXECUTE_TYPE"
              :key="index"
              @change="changeExecuteType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <div v-if="ruleForm.executeType == 1" class="date-flex">
            <el-form-item label="执行时间" prop="nextTime1">
              <div class="edit-date-wrap">
                <el-date-picker
                  class="weekData"
                  v-model="ruleForm.nextTime1"
                  value-format="YYYY-MM-DD"
                  popper-class="qc-date"
                  placeholder="请选择日期"
                  type="date"
                />
              </div>
            </el-form-item>
            <el-form-item label="" prop="nextTime2" style="margin-left: -260px">
              <div class="edit-date-wrap1">
                <el-time-select
                  v-model="ruleForm.nextTime2"
                  start="00:00"
                  step="00:10"
                  end="23:50"
                  placeholder="请选择时间"
                />
              </div>
            </el-form-item>
          </div>
          <el-form-item
            label="总执行次数"
            prop="totalCount"
            v-if="ruleForm.executeType == 2"
          >
            <el-input
              v-model.trim="ruleForm.totalCount"
              maxlength="9"
              placeholder="请输入总执行次数"
              clearable
            />
          </el-form-item>
          <el-form-item
            label=""
            prop="executePeriod"
            v-if="ruleForm.executeType == 2"
          >
            <el-radio-group
              v-model="ruleForm.executePeriod"
              v-for="(item, index) in executePeriodData"
              :key="index"
              @change="changeExecutePeriod"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label=""
            prop="executeTime"
            v-if="ruleForm.executeType == 2 && ruleForm.executePeriod == '0'"
          >
            <div class="edit-date-wrap">
              <el-time-select
                v-model="ruleForm.executeTime"
                start="00:00"
                step="00:10"
                end="23:50"
                placeholder="请选择时间"
              />
            </div>
          </el-form-item>
          <div
            class="date-flex"
            v-if="ruleForm.executeType == 2 && ruleForm.executePeriod == '1'"
          >
            <el-form-item label="" prop="executeWeek">
              <qc-select
                class="weekData"
                :value="ruleForm.executeWeek"
                :options="WEEK"
                placeholder="请选择星期"
                @change="handleWeek"
              >
              </qc-select>
            </el-form-item>
            <el-form-item
              label=""
              prop="executeTime"
              style="margin-left: -130px"
            >
              <div class="edit-date-wrap edit-date-wrap2">
                <el-time-select
                  v-model="ruleForm.executeTime"
                  start="00:00"
                  step="00:10"
                  end="23:50"
                  placeholder="请选择时间"
                />
              </div>
            </el-form-item>
          </div>
          <div
            class="date-flex"
            v-if="ruleForm.executeType == 2 && ruleForm.executePeriod == '2'"
          >
            <el-form-item label="" prop="executeDate">
              <qc-select
                class="weekData"
                :value="ruleForm.executeDate"
                :options="optionsS.date"
                placeholder="请选择日期"
                @change="handleDate"
              >
              </qc-select>
            </el-form-item>
            <el-form-item
              label=""
              prop="executeTime"
              style="margin-left: -130px"
            >
              <div class="edit-date-wrap edit-date-wrap2">
                <el-time-select
                  v-model="ruleForm.executeTime"
                  start="00:00"
                  step="00:10"
                  end="23:50"
                  placeholder="请选择时间"
                />
              </div>
            </el-form-item>
          </div>
          <el-form-item
            label=""
            v-if="ruleForm.executeType == 2 && ruleForm.executePeriod == '2'"
            class="has-tips"
          >
            <div class="tip">
              <div class="icon"></div>
              <span
                >选择的日期在某月份无该日期时，则跳过该月的执行，示例：选择30号，2月份不执行该任务</span
              >
            </div>
          </el-form-item>
        </el-form>
        <ImportDialog
          ref="importDialogRef"
          @user-data="userData"
        ></ImportDialog>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>
  
<script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';
import Head from '@/components/head/index.vue';
import QcTree from '@/components/qcTree/index.vue';
import ImportDialog from '@/components/qcDialog/importDialog.vue';
import {
  queryAllCompany,
  queryVehicle,
  queryLabelListByName,
} from '@/service/apis/org';
import {
  subsidyTaskSave,
  subsidyTaskUpdate,
  subsidyTaskGetById,
} from '@/service/apis/user';
import { IS_DECIMAL_4, IS_DECIMAL_2, IS_INTEGER } from '@/utils/verify';
import { TASK_TYPE, EXECUTE_TYPE, WEEK } from '@/utils/dictionaries';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;
const ruleFormRef = ref<FormInstance>();
const ruleFormOtherRef = ref<FormInstance>();
const importDialogRef = ref();

let targetTypeData = reactive([] as any);
targetTypeData = [
  {
    value: '0',
    label: '选择企业',
  },
  {
    value: '1',
    label: '选择标签',
  },
  {
    value: '2',
    label: '选择单用户',
  },
];

let executePeriodData = reactive([] as any);
executePeriodData = [
  {
    value: '0',
    label: '每日执行',
  },
  {
    value: '1',
    label: '每周执行',
  },
  {
    value: '2',
    label: '每月执行',
  },
];

let optionsS = reactive({
  org: [] as any,
  city: [] as any,
  card: [] as any,
  date: [] as any,
  treeData: [] as any,
  labelTreeData: [] as any,
  setCompanyChecked: [] as any,
  setLabelChecked: [] as any,
  file: [] as any,
});

const dateDate = Array.from({ length: 31 }, (_, i) => 1 + i);
console.log('dateDate', dateDate);
dateDate.forEach((value: any) => {
  optionsS.date.push({
    label: value,
    value: value,
  });
});

const userData = (data: any) => {
  ruleForm.userTargetIds = data;
};

// 获取归属运营商
queryAllCompany({ isDefault: false }).then((res: any) => {
  if (res) {
    optionsS.org = [...res.listMap];
  }
});

// // 选择企业
// queryCarList({}).then((res: any) => {
//   if (res) {
// 		console.log([...res]);
//     optionsS.treeData = [...res];
//   }
// });
// 获取车辆机构
queryVehicle({ isDefault: false }).then((res: any) => {
  if (res) {
    optionsS.treeData = res;
  }
});

// 选择标签
queryLabelListByName({}).then((res: any) => {
  if (res) {
    console.log([...res.listMap]);
    optionsS.labelTreeData = [...res.listMap];
  }
});

let dialogVisible = ref(false);
// 关闭弹框
const hide = () => {
  dialogVisible.value = false;
};
// 打开弹窗并赋值
const uploadUser = () => {
  importDialogRef.value?.show();
  // dialogVisible.value = true;
};

const handleCheck = (data: any, checkedData: any, checkedChildData: any) => {
  ruleForm.treeId = checkedChildData;
  const aa = ruleForm?.treeId.join(',');
  ruleForm.targetIds = aa;
  ruleFormRef.value?.validateField('treeId');
};

const handleCheck1 = (data: any, checkedData: any, checkedChildData: any) => {
  ruleForm.treeId1 = checkedChildData;
  const aa = ruleForm?.treeId1.join(',');
  ruleForm.targetIds = aa;
  ruleFormRef.value?.validateField('treeId1');
};

const changeExecuteType = (e: any) => {
  ruleForm.executePeriod = '0';
  ruleForm.totalCount = '';
  ruleForm.executeTime = '';
  ruleForm.executeDate = undefined as unknown;
  ruleForm.executeWeek = undefined as unknown;
};

const changeExecutePeriod = (e: any) => {
  ruleForm.executeTime = '';
  ruleForm.executeDate = undefined as unknown;
  ruleForm.executeWeek = undefined as unknown;
};
const checkFile = (rule: any, value: any, callback: any) => {
  if (value.length == 0) {
    callback(new Error('请上传文件'));
  }
  callback();
};

let dialogRuleForm = reactive({
  file: [] as any,
});
const dialogRules = reactive<FormRules>({
  file: [
    { required: true, message: '请上传用户', trigger: 'change' },
    { validator: checkFile, trigger: 'change' },
  ],
});

let ruleForm = reactive({
  id: '',
  name: '',
  amount: '',
  originalAccountId: undefined as unknown,
  originalAccountName: '',
  taskType: 1,
  targetType: '0',
  executeType: 1,
  executePeriod: '0',
  totalCount: '',
  executeWeek: undefined as unknown,
  nextTime: '',
  signTime: '',
  executeTime: '',
  treeId: [],
  treeId1: [],
  targetIds: '',
  userTargetIds: '',
  executeDate: undefined as unknown,
  nextTime1: '',
  nextTime2: '',
});

const checkTreeVehicles = (rule: any, value: any, callback: any) => {
  const arr: any = [];
  const treeOrg = companyTree.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  if (arr.length === 0) {
    callback(new Error('请选择具体的用户企业（车辆机构）'));
  }
  callback();
};
const rules = reactive<FormRules>({
  name: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
  originalAccountId: [
    { required: true, message: '请选择任务支付钱包', trigger: 'change' },
  ],
  taskType: [{ required: true, message: '请选择任务模式', trigger: 'change' }],
  amount: [
    { required: true, message: '请输入金额', trigger: 'blur' },
    {
      pattern: IS_DECIMAL_2,
      message: '请输入正确的金额，保留2位小数',
      trigger: 'blur',
    },
  ],
  targetType: [
    { required: true, message: '请选择执行目标', trigger: 'change' },
  ],
  treeId: [
    { required: true, message: '请选择执行目标', trigger: 'change' },
    { validator: checkTreeVehicles, trigger: ['blur', 'change'] },
  ],
  treeId1: [{ required: true, message: '请选择执行目标', trigger: 'change' }],
  executeType: [
    { required: true, message: '请选择选择模式', trigger: ['blur', 'change'] },
  ],
  nextTime1: [
    { required: true, message: '请选择执行时间', trigger: ['blur', 'change'] },
  ],
  nextTime2: [
    { required: true, message: '请选择执行时间', trigger: ['blur', 'change'] },
  ],
  totalCount: [
    {
      required: true,
      message: '请输入总执行次数',
      trigger: ['blur', 'change'],
    },
    {
      pattern: IS_INTEGER,
      message: '请输入正确的总执行次数，正整数',
      trigger: 'blur',
    },
  ],
  userTargetIds: [
    { required: true, message: '请输入用户账号', trigger: ['blur', 'change'] },
  ],
  executeWeek: [
    { required: true, message: '请选择星期', trigger: ['blur', 'change'] },
  ],
  executeDate: [
    { required: true, message: '请选择日期', trigger: ['blur', 'change'] },
  ],
  executeTime: [
    { required: true, message: '请选择时间', trigger: ['blur', 'change'] },
  ],
});

const handleTargetType = (e: any) => {
  console.log(e);
  if (e == 0) {
    ruleForm.treeId = [];
  } else if (e == 1) {
    ruleForm.treeId1 = [];
  } else if (e == 2) {
    ruleForm.userTargetIds = '';
  }
};

const handleChangeOrg = (e: any) => {
  ruleForm.originalAccountId = e;
};

const handleWeek = (e: any) => {
  ruleForm.executeWeek = e;
};
const handleDate = (e: any) => {
  ruleForm.executeDate = e;
};

const back = () => {
  router.go(-1);
};

let companyTree = ref();
let labelTree = ref();
// 编辑回填数据
if (id) {
  subsidyTaskGetById(Number(id)).then((res: any) => {
    ruleForm.id = res.id;
    ruleForm.name = res.name;
    ruleForm.amount = res.amount;
    ruleForm.originalAccountId = res.originalAccountId;
    ruleForm.originalAccountName = res.originalAccountName;
    ruleForm.taskType = res?.taskType;
    ruleForm.targetType = res?.targetType.toString();
    ruleForm.executeType = res?.executeType;
    ruleForm.executePeriod =
      res.executeType == 2 ? res?.executePeriod.toString() : '';
    ruleForm.totalCount = res.totalCount;
    ruleForm.executeWeek = res.executeWeek ? res.executeWeek.toString() : '';
    ruleForm.executeDate = res.executeDate ? res.executeDate.toString() : '';
    ruleForm.nextTime = res.nextTime;
    ruleForm.signTime = res.signTime;
    ruleForm.executeTime = res.executeTime;
    if (ruleForm.targetType == '0') {
      ruleForm.treeId = res.targetIds.split(',');
    } else if (ruleForm.targetType == '1') {
      ruleForm.treeId1 = res.targetIds.split(',');
    }
    ruleForm.userTargetIds = res.targetIds;
    if (res.nextTime) {
      console.log(res.nextTime.split(' '));
      ruleForm.nextTime1 = res.nextTime.split(' ')[0];
      const aa = res.nextTime.split(' ')[1].split(':')[0];
      const bb = res.nextTime.split(' ')[1].split(':')[1];
      ruleForm.nextTime2 = `${aa}:${bb}`;
    }

    if (ruleForm.targetType == '0') {
      setTimeout(() => {
        const targetIds = res?.targetIds.split(',');
        console.log(companyTree.value);

        companyTree.value!.setCheckedKeys(targetIds);
      }, 500);
    }

    if (ruleForm.targetType == '1') {
      setTimeout(() => {
        const targetIds = res?.targetIds.split(',');
        labelTree.value!.setCheckedKeys(targetIds);
      }, 500);
    }
  });
}

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (ruleForm.executeType == 1 && ruleForm.nextTime1 && ruleForm.nextTime2) {
    ruleForm.nextTime = `${ruleForm.nextTime1} ${ruleForm.nextTime2}:00`;
  } else {
    ruleForm.nextTime = '';
  }

  if (ruleForm.targetType == '0') {
    const arr: any = [];
    const treeOrg = companyTree.value?.getCheckedNodes();
    treeOrg.forEach((item: any) => {
      if (item.type !== 'CHANNEL') {
        arr.push(item.id);
      }
    });
    ruleForm.targetIds = arr.join(',');
    // ruleForm.targetIds = ruleForm.treeId.join(',');
  }
  if (ruleForm.targetType == '1') {
    ruleForm.targetIds = ruleForm.treeId1.join(',');
  }
  if (ruleForm.targetType == '2') {
    ruleForm.targetIds = ruleForm.userTargetIds;
  }
  if (!ruleFormRef.value || !ruleFormOtherRef.value) return;
  try {
    await Promise.all([
      ruleFormRef.value.validate(),
      ruleFormOtherRef.value.validate(),
    ]);
  } catch (fields: any) {
    for (const key in ruleForm) {
      if (fields[key]) {
        ruleFormRef.value.scrollToField(key);
        ruleFormOtherRef.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  if (id) {
    console.log(ruleForm);
    subsidyTaskUpdate(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    subsidyTaskSave(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>
<style lang="scss">
.weekData {
  width: 144px !important;
}
.edit-page-wrap {
  .icon-download {
    color: #5073f7;
  }
}

.date-flex {
  display: flex;
  .el-input__wrapper {
    width: 130px !important;
  }
  .edit-date-wrap1 {
    // margin-left: -240px;
    .el-input.el-input--prefix.el-input--suffix {
      width: 160px !important;
    }
  }
  .edit-date-wrap2 {
    .el-input.el-input--prefix.el-input--suffix {
      width: 160px !important;
    }
  }
}
</style>